package com.unlcn.ils.wms.backend.service.outbound.impl;

import cn.huiyunche.commons.domain.ResultDTOWithPagination;
import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.unlcn.ils.wms.backend.bo.baseDataBO.WmsWarehouseBO;
import com.unlcn.ils.wms.backend.bo.outboundBO.CreatePreparationPlanBO;
import com.unlcn.ils.wms.backend.bo.outboundBO.GetShipmentPLanListBO;
import com.unlcn.ils.wms.backend.bo.outboundBO.WmsShipmentPlanFromTmsBO;
import com.unlcn.ils.wms.backend.dto.outboundDTO.ShipmentPlanEmptyDTO;
import com.unlcn.ils.wms.backend.enums.*;
import com.unlcn.ils.wms.backend.service.baseData.WmsWarehouseService;
import com.unlcn.ils.wms.backend.service.inbound.WmsInventoryService;
import com.unlcn.ils.wms.backend.service.outbound.WmsShipmentPlanService;
import com.unlcn.ils.wms.backend.service.webservice.bo.WmsShipmentPlanResultDTO;
import com.unlcn.ils.wms.backend.service.webservice.client.WmsJmDcsService;
import com.unlcn.ils.wms.backend.service.webservice.dto.ResultForDcsInorOutDetailsDTO;
import com.unlcn.ils.wms.backend.service.webservice.vo.WmsShipmentPlanVO;
import com.unlcn.ils.wms.backend.util.DateUtils;
import com.unlcn.ils.wms.base.businessDTO.outbound.WmsShipmentPlanVehicleDTO;
import com.unlcn.ils.wms.base.mapper.extmapper.WmsHandoverOrderCustomMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.WmsPreparationVehicleDetailCustomMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.WmsShipmentPlanExtMapper;
import com.unlcn.ils.wms.base.mapper.inbound.WmsTmsLogMapper;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsDcsLogMapper;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsHandoverOrderMapper;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsShipmentCancelExcpMapper;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsShipmentPlanCancelMapper;
import com.unlcn.ils.wms.base.mapper.outbound.WmsDetailUpdateRecordMapper;
import com.unlcn.ils.wms.base.mapper.outbound.WmsPreparationPlanMapper;
import com.unlcn.ils.wms.base.mapper.outbound.WmsPreparationVehicleDetailMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsShipmentPlanMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsShipmentUpdatemqLogMapper;
import com.unlcn.ils.wms.base.mapper.sys.SysUserMapper;
import com.unlcn.ils.wms.base.model.inbound.WmsTmsLogWithBLOBs;
import com.unlcn.ils.wms.base.model.junmadcs.*;
import com.unlcn.ils.wms.base.model.outbound.WmsDetailUpdateRecord;
import com.unlcn.ils.wms.base.model.outbound.WmsPreparationPlan;
import com.unlcn.ils.wms.base.model.outbound.WmsPreparationVehicleDetail;
import com.unlcn.ils.wms.base.model.outbound.WmsPreparationVehicleDetailExample;
import com.unlcn.ils.wms.base.model.stock.*;
import com.unlcn.ils.wms.base.model.sys.SysUser;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by DELL on 2017/9/22.
 */
@Service
public class WmsShipmentPlanServiceImpl implements WmsShipmentPlanService {

    private static final String TYPE = "O";
    private DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    private Logger logger = LoggerFactory.getLogger(WmsShipmentPlanServiceImpl.class);

    @Value("${tms.pickup.host.url}")
    private String propertyUrl;
    @Value("${tms.pickup.host.timeout}")
    private String propertyTime;
    @Value("${tms.encode.key}")
    private String propertyKey;

    @Autowired
    private WmsTmsLogMapper wmsTmsLogMapper;
    @Autowired
    WmsShipmentPlanMapper wmsShipmentPlanMapper;
    @Autowired
    WmsShipmentPlanExtMapper wmsShipmentPlanExtMapper;
    @Autowired
    WmsPreparationPlanMapper wmsPreparationPlanMapper;
    @Autowired
    WmsPreparationVehicleDetailMapper wmsPreparationVehicleDetailMapper;
    @Autowired
    private WmsInventoryService wmsInventoryService;
    @Autowired
    private WmsHandoverOrderCustomMapper wmsHandoverOrderCustomMapper;
    @Autowired
    private WmsHandoverOrderMapper wmsHandoverOrderMapper;
    @Autowired
    private WmsPreparationVehicleDetailCustomMapper vehicleDetailCustomMapper;
    @Autowired
    private WmsPreparationVehicleDetailMapper preparationVehicleDetailMapper;
    @Autowired
    private WmsJmDcsService wmsJmDcsService;
    @Autowired
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private WmsShipmentPlanCancelMapper wmsShipmentPlanCancelMapper;
    @Autowired
    private WmsShipmentCancelExcpMapper wmsShipmentCancelExcpMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private WmsShipmentUpdatemqLogMapper wmsShipmentUpdatemqLogMapper;
    @Autowired
    private WmsDetailUpdateRecordMapper detailUpdateRecordMapper;//车辆详情变更记录
    @Autowired
    private WmsDcsLogMapper wmsDcsLogMapper;

    @Override
    public List<ResultForDcsInorOutDetailsDTO> saveShipmentList(WmsShipmentPlanVO[] planVOS, String s_body, String s_head) {
        logger.info("WmsBusinessServiceImpl.saveShipmentList param{}", JSONObject.toJSONString(planVOS));
        //记录日志
        Runnable runnable = () -> {
            WmsDcsLogWithBLOBs log = new WmsDcsLogWithBLOBs();
            log.setMsgBody(s_body);
            log.setMsgHead(s_head);
            log.setSendType("IN");
            log.setGmtCreate(new Date());
            log.setGmtUpdate(new Date());
            log.setUrl("WmsBusinessServiceImpl.saveShipmentList");
            wmsDcsLogMapper.insertSelective(log);
            logger.info("WmsBusinessServiceImpl.saveShipmentList  保存发运计划成功");
        };
        new Thread(runnable).start();

        List<ResultForDcsInorOutDetailsDTO> resultDetails = Lists.newArrayList();
        //格式校验
        for (WmsShipmentPlanVO planVO : planVOS) {
            //非空校验
            WmsShipmentPlan wmsShipmentPlan = new WmsShipmentPlan();
            BeanUtils.copyProperties(planVO, wmsShipmentPlan);
            WmsShipmentPlanResultDTO wmsShipmentPlanResultDTO = check(planVO);

            ResultForDcsInorOutDetailsDTO detailsDTO = new ResultForDcsInorOutDetailsDTO();

            if (Objects.isNull(wmsShipmentPlanResultDTO)) {
                //非空验证通过
                //格式校验
                if (StringUtils.isNotBlank(planVO.getSpEstimateLoadingTime())) {
                    try {
                        wmsShipmentPlan.setSpEstimateLoadingTime(fmt.parse(planVO.getSpEstimateLoadingTime()));
                    } catch (ParseException e) {
                        logger.error("WmsSapBusinessServiceImpl.saveShipmentList param{}", e);
                        //设置明细
                        detailsDTO.setSpOrderNo(planVO.getSpOrderNo());
                        detailsDTO.setSpGroupBoardNo(planVO.getSpGroupBoardNo());
                        detailsDTO.seteMsg("预计装车时间格式不正确(yyyy-MM-dd)");
                        detailsDTO.setSpMaterialCode(planVO.getSpMaterialCode());
                        resultDetails.add(detailsDTO);
                        //return resultDetails;
                    }
                }
                if (StringUtils.isNotBlank(planVO.getSpGroupBoardQuantity())) {
                    try {
                        wmsShipmentPlan.setSpGroupBoardQuantity(Long.valueOf(planVO.getSpGroupBoardQuantity()));
                    } catch (NumberFormatException e) {
                        logger.error("WmsSapBusinessServiceImpl.saveShipmentList param{}", e);
                        //设置明细
                        detailsDTO.setSpOrderNo(planVO.getSpOrderNo());
                        detailsDTO.setSpGroupBoardNo(planVO.getSpGroupBoardNo());
                        detailsDTO.seteMsg("组板数量输入值不正确,请输入数字");
                        detailsDTO.setSpMaterialCode(planVO.getSpMaterialCode());
                        resultDetails.add(detailsDTO);
                        //return resultDetails;
                        //throw new NumberFormatException("组板数量输入值不正确,请输入数字");
                    }
                }

                if (CollectionUtils.isEmpty(resultDetails)) {
                    //重复性校验 -- 调整校验订单号,防止dcs发送发运计划超时(重新组板)
                    WmsShipmentPlanExample wmsShipmentPlanExample = new WmsShipmentPlanExample();
                    wmsShipmentPlanExample.createCriteria().andSpOrderNoEqualTo(planVO.getSpOrderNo().trim())
                            .andSpIsRejectEqualTo(ShipmentPlanRejectStatusEnum.NO_REJECT.getCode())
                            .andSpMaterialCodeEqualTo(planVO.getSpMaterialCode().trim());
                    List<WmsShipmentPlan> wmsShipmentPlans = wmsShipmentPlanMapper.selectByExample(wmsShipmentPlanExample);
                    if (CollectionUtils.isNotEmpty(wmsShipmentPlans)) {
                        //设置明细
                        detailsDTO.setSpOrderNo(planVO.getSpOrderNo());
                        detailsDTO.setSpGroupBoardNo(planVO.getSpGroupBoardNo());
                        detailsDTO.seteMsg("订单号:" + planVO.getSpOrderNo() +
                                "物料编码:" + planVO.getSpMaterialCode() + ",已经在wms存在");
                        detailsDTO.setSpMaterialCode(planVO.getSpMaterialCode());
                        resultDetails.add(detailsDTO);
                        //return resultDetails;
                        //throw new BusinessException("该行Id:" + planVO.getSpLineId() + "已经在wms存在");
                    }
                    if (CollectionUtils.isEmpty(resultDetails)) {
                        //插入数据
                        try {
                            if ((StringUtils.isNotBlank(wmsShipmentPlan.getSpDeliverWarehouseCode()))
                                    && (!wmsShipmentPlan.getSpDeliverWarehouseCode().contains("CQ"))) {
                                if (wmsShipmentPlan.getSpDeliverWarehouseCode().contains("CS01")) {
                                    wmsShipmentPlan.setSpWhCode(WhCodeEnum.JM_CS.getValue());
                                    wmsShipmentPlan.setSpWhName(WhCodeEnum.JM_CS.getText());
                                    wmsShipmentPlan.setSpDeliverWarehouseCode(WhCodeEnum.JM_CS.getValue());
                                    wmsShipmentPlan.setSpDeliverWarehouseName(WhCodeEnum.JM_CS.getText());
                                }
                                if (wmsShipmentPlan.getSpDeliverWarehouseCode().contains("XY01")) {
                                    wmsShipmentPlan.setSpWhCode(WhCodeEnum.JM_XY.getValue());
                                    wmsShipmentPlan.setSpWhName(WhCodeEnum.JM_XY.getText());
                                    wmsShipmentPlan.setSpDeliverWarehouseCode(WhCodeEnum.JM_XY.getValue());
                                    wmsShipmentPlan.setSpDeliverWarehouseName(WhCodeEnum.JM_XY.getText());
                                }
                                //调拨发运经销商code  对应收货仓库code
                                if (StringUtils.isNotBlank(wmsShipmentPlan.getSpDealerCode())
                                        && "CS01".equals(wmsShipmentPlan.getSpDealerCode())) {
                                    wmsShipmentPlan.setSpDealerCode(WhCodeEnum.JM_CS.getValue());
                                }
                                if (StringUtils.isNotBlank(wmsShipmentPlan.getSpDealerCode())
                                        && "XY01".equals(wmsShipmentPlan.getSpDealerCode())) {
                                    wmsShipmentPlan.setSpDealerCode(WhCodeEnum.JM_XY.getValue());
                                }

                            }
                            wmsShipmentPlan.setGmtUpdate(new Date());
                            wmsShipmentPlan.setSpCarColour(planVO.getSpCarColour());
                            String materialCode = planVO.getSpMaterialCode();
                            if (StringUtils.isNotBlank(materialCode)) {
                                wmsShipmentPlan.setSpCarColourCode(materialCode.substring(materialCode.length() - 2, materialCode.length() - 1));
                            }
                            wmsShipmentPlan.setGmtCreate(new Date());
                            wmsShipmentPlan.setSpCustomerCode(WmsCustomerEnum.JM.getCode());
                            wmsShipmentPlan.setSpCustomerName(WmsCustomerEnum.JM.getName());
                            wmsShipmentPlan.setSpSendBusinessFlag(String.valueOf(SendBusinessFlagEnum.SEND_N.getValue()));
                            wmsShipmentPlan.setSpSysSource(WmsSysSourceEnum.DCS_IMPORT.getValue());
                            wmsShipmentPlan.setSpIsReject(ShipmentPlanRejectStatusEnum.NO_REJECT.getCode());
                            wmsShipmentPlan.setSpRejectNum(0L);
                            wmsShipmentPlanMapper.insert(wmsShipmentPlan);
                        } catch (Exception ex) {
                            logger.error("WmsBusinessServiceImpl.saveShipmentList param{}", ex);
                            //设置明细
                            detailsDTO.setSpOrderNo(planVO.getSpOrderNo());
                            detailsDTO.setSpGroupBoardNo(planVO.getSpGroupBoardNo());
                            detailsDTO.seteMsg("该行Id:" + planVO.getSpLineId() + "插入失败!");
                            detailsDTO.setSpMaterialCode(planVO.getSpMaterialCode());
                            //return resultDetails;
                            //throw new BusinessException("发运计划发送异常，请再次发送");
                        }
                    }

                }
            } else {
                //验证不过
                //设置明细
                detailsDTO.setSpOrderNo(planVO.getSpOrderNo());
                detailsDTO.setSpGroupBoardNo(planVO.getSpGroupBoardNo());
                detailsDTO.seteMsg(wmsShipmentPlanResultDTO.geteMsg());
                detailsDTO.setSpMaterialCode(planVO.getSpMaterialCode());
                resultDetails.add(detailsDTO);
                //return resultDetails;
                //throw new BusinessException(wmsShipmentPlanResultDTO.geteMsg());
            }
        }
        return resultDetails;
    }

    /**
     * 发运计划数据验证，现在还只做了非空验证
     *
     * @param planVO 参数封装
     * @return 返回值
     */
    private WmsShipmentPlanResultDTO check(WmsShipmentPlanVO planVO) {

        StringBuilder eMsg = new StringBuilder();
        if (StringUtils.isBlank(planVO.getSpOrderNo())) {//订单号
            eMsg.append("订单号为空；");
        }
        if (Objects.equals(planVO.getSpLineId(), null)) {//订单行Id
            eMsg.append("订单行Id为空；");
        }
        if (Objects.equals(planVO.getSpDlvType(), null)) {//发运类型为空
            eMsg.append("发运类型为空；");
        }
        //if(StringUtils.isBlank(planVO.getSpVehicleCode())) {//车型code
        //    eMsg.append("车型代码为空；");
        //}
        //if(StringUtils.isBlank(planVO.getSpVehicleName())) {//车型name
        //    eMsg.append("车型名称为空；");
        //}
        //if(StringUtils.isBlank(planVO.getSpConfigure())) {//配置
        //    eMsg.append("配置为空；");
        //}
        //if(StringUtils.isBlank(planVO.getSpCarColour())) {//颜色
        //    eMsg.append("颜色为空；");
        //}
        if (StringUtils.isBlank(planVO.getSpMaterialCode())) {//物料代码
            eMsg.append("物料代码为空；");
        }
        if (planVO.getSpGroupBoardQuantity() == null) {//组板数量
            eMsg.append("组板数量为空；");
        }

        //if(StringUtils.isBlank(planVO.getSpDealerCode())) {//经销商代码
        //    eMsg.append("经销商代码为空；");
        //}
        //if(StringUtils.isBlank(planVO.getSpDealerName())) {//经销商名称
        //    eMsg.append("经销商名称为空；");
        //}
        //if(StringUtils.isBlank(planVO.getSpProvince())) {//收货省
        //    eMsg.append("收货省为空；");
        //}
        //if(StringUtils.isBlank(planVO.getSpCity())) {//收货市
        //    eMsg.append("收货市为空；");
        //}
        //if(StringUtils.isBlank(planVO.getSpDistrictCounty())) {//收货区县
        //    eMsg.append("收货区县为空；");
        //}
        //if(StringUtils.isBlank(planVO.getSpDetailedAddress())) {//收货详细地址
        //    eMsg.append("收货详细地址为空；");
        //}
        if (StringUtils.isBlank(planVO.getSpCarrier())) {//承运商
            eMsg.append("承运商为空；");
        }
        if (planVO.getSpEstimateLoadingTime() == null) {//预计装车时间
            eMsg.append("预计装车时间为空；");
        }
        if (planVO.getSpDlvType().equals(WmsShipmentPlanDlvTypeEnum.A1.getValue()) && StringUtils.isBlank(planVO.getSpFoundType())) {
            eMsg.append("该行Id:").append(planVO.getSpLineId()).append("资金类型为空；");
        }
        if (planVO.getSpDlvType().equals(WmsShipmentPlanDlvTypeEnum.A1.getValue()) && StringUtils.isBlank(planVO.getSpIsRemain())) {
            eMsg.append("该行Id:").append(planVO.getSpLineId()).append("是否保留合格证为空;");
        }
        if (eMsg.length() > 0) {
            WmsShipmentPlanResultDTO wmsShipmentPlanResultDTO = new WmsShipmentPlanResultDTO();
            wmsShipmentPlanResultDTO.setSpOrderNo(planVO.getSpOrderNo());
            wmsShipmentPlanResultDTO.setSpGroupBoardNo(planVO.getSpGroupBoardNo());
            wmsShipmentPlanResultDTO.setSpMaterialCode(planVO.getSpMaterialCode());
            wmsShipmentPlanResultDTO.seteMsg(eMsg.toString());
            return wmsShipmentPlanResultDTO;
        } else {
            return null;
        }
    }

    @Override
    public ResultDTOWithPagination<Object> getShipmentPLanList(GetShipmentPLanListBO bo) {
        logger.info("WmsShipmentPlanServiceImpl.getShipmentPLanList param : ", bo);
        try {
            ResultDTOWithPagination<Object> result = new ResultDTOWithPagination<>(true, null, "查询成功", bo);
            Map<String, Object> paramMap = new HashMap<>();
            String orderByClause = StringUtils.isNotEmpty(bo.getOrder()) ? bo.getOrder() : " gmt_create desc ";

            if (null != bo.getSpWhCode() && StringUtils.isNotEmpty(bo.getSpWhCode())) {
                paramMap.put("whCode", bo.getSpWhCode());
            }

            //if (null != bo && null != bo.getSpGroupBoardNo()
            //        && StringUtils.isNotEmpty(bo.getSpGroupBoardNo())) {
            //    paramMap.put("groupBoardNo", bo.getSpGroupBoardNo());
            //}
            //TODO 指令号
            if (StringUtils.isNotBlank(bo.getSpDispatchNo())) {
                paramMap.put("spDispatchNo", bo.getSpDispatchNo());
            }

            if (null != bo.getSpSendBusinessFlag() && StringUtils.isNotEmpty(bo.getSpSendBusinessFlag())) {
                paramMap.put("sendBusinessFlag", bo.getSpSendBusinessFlag());
            } else {
                if (!paramMap.containsKey("spDispatchNo")) {
                    paramMap.put("sendBusinessFlag", SendBusinessFlagEnum.SEND_N.getValue());
                }
            }

            if (null != bo.getSpOrderNo() && StringUtils.isNotEmpty(bo.getSpOrderNo())) {
                paramMap.put("orderNo", bo.getSpOrderNo());
            }

            if (null != bo.getSpCustomerName() && StringUtils.isNotEmpty(bo.getSpCustomerName())) {
                paramMap.put("customerName", bo.getSpCustomerName());
            }

            if (null != bo.getSpCarrier() && StringUtils.isNotEmpty(bo.getSpCarrier())) {
                paramMap.put("carrier", bo.getSpCarrier());
            }

            if (null != bo.getSpOrigin() && StringUtils.isNotEmpty(bo.getSpOrigin())) {
                paramMap.put("origin", bo.getSpOrigin());
            }

            if (null != bo.getSpDest() && StringUtils.isNotEmpty(bo.getSpDest())) {
                paramMap.put("dest", bo.getSpDest());
            }

            if (null != bo.getGmtCreateBegin() && StringUtils.isNotEmpty(bo.getGmtCreateBegin())) {
                paramMap.put("createDateBegin", bo.getGmtCreateBegin() + " 00:00:00");

            }

            if (null != bo.getGmtCreateEnd() && StringUtils.isNotEmpty(bo.getGmtCreateEnd())) {
                paramMap.put("createDateEnd", bo.getGmtCreateEnd() + " 23:59:59");
            }

            Integer count = wmsShipmentPlanExtMapper.countListByGroup(paramMap);
            bo.setTotalRecord(null == count ? 0 : count);

            paramMap.put("limitStart", bo.getStartIndex());
            paramMap.put("limitEnd", bo.getPageSize());
            paramMap.put("orderByClause", orderByClause);

            List<WmsShipmentPlan> list = wmsShipmentPlanExtMapper.getListByGroup(paramMap);
            result.setData(list);
            return result;
        } catch (Exception ex) {
            logger.error("WmsShipmentPlanServiceImpl.getShipmentPLanList error : ", ex);
            throw new BusinessException("获取数据异常");
        }
    }

    /**
     * 发运计划列表 - 君马
     * 2018-3-8 调整默认不展示未处理已驳回数据
     *
     * @param bo 参数封装
     * @return 返回值
     */
    @Override
    public ResultDTOWithPagination<Object> getShipmentPLanListForNew(GetShipmentPLanListBO bo) {
        logger.info("WmsShipmentPlanServiceImpl.getShipmentPLanListForNew param : ", bo);
        try {
            ResultDTOWithPagination<Object> result = new ResultDTOWithPagination<>(true, null, "查询成功", bo);
            Map<String, Object> paramMap = new HashMap<>();
            String orderByClause = StringUtils.isNotEmpty(bo.getOrder()) ? bo.getOrder() : " gmt_create desc ";

            //组版单号
            if (StringUtils.isNotBlank(bo.getSpGroupBoardNo())) {
                paramMap.put("groupBoardNo", bo.getSpGroupBoardNo());
            }

            if (StringUtils.isNotBlank(bo.getSpWhCode())) {
                paramMap.put("whCode", bo.getSpWhCode());
            }

            if (StringUtils.isNotBlank(bo.getSpSendBusinessFlag())) {
                paramMap.put("sendBusinessFlag", bo.getSpSendBusinessFlag());
            } else {
                if (!paramMap.containsKey("spDispatchNo")) {
                    paramMap.put("sendBusinessFlag", SendBusinessFlagEnum.SEND_N.getValue());
                }
            }

            if (null != bo.getSpOrderNo() && StringUtils.isNotBlank(bo.getSpOrderNo())) {
                paramMap.put("orderNo", bo.getSpOrderNo());
            }

            if (null != bo.getSpCustomerName() && StringUtils.isNotBlank(bo.getSpCustomerName())) {
                paramMap.put("customerName", bo.getSpCustomerName());
            }

            if (null != bo.getSpCarrier() && StringUtils.isNotBlank(bo.getSpCarrier())) {
                paramMap.put("carrier", bo.getSpCarrier());
            }

            if (StringUtils.isNotBlank(bo.getSpOrigin())) {
                paramMap.put("origin", bo.getSpOrigin());
            }

            if (StringUtils.isNotBlank(bo.getSpDest())) {
                paramMap.put("dest", bo.getSpDest());
            }

            if (StringUtils.isNotBlank(bo.getGmtCreateBegin())) {
                paramMap.put("createDateBegin", bo.getGmtCreateBegin() + " 00:00:00");

            }

            if (StringUtils.isNotBlank(bo.getGmtCreateEnd())) {
                paramMap.put("createDateEnd", bo.getGmtCreateEnd() + " 23:59:59");
            }

            //默认设置
            paramMap.put("spSysSource", WmsSysSourceEnum.DCS_IMPORT.getValue());

            paramMap.put("spNotReject", StringUtils.isBlank(bo.getSpIsRejected()) ?
                    ShipmentPlanRejectStatusEnum.NO_REJECT.getCode() : bo.getSpIsRejected());

            //Integer count = wmsShipmentPlanExtMapper.countListByGroup(paramMap);
            Integer count = wmsShipmentPlanExtMapper.countListForNew(paramMap);
            bo.setTotalRecord(null == count ? 0 : count);
            paramMap.put("limitStart", bo.getStartIndex());
            paramMap.put("limitEnd", bo.getPageSize());
            paramMap.put("orderByClause", orderByClause);

            //List<WmsShipmentPlan> list = wmsShipmentPlanExtMapper.getListByGroup(paramMap);
            List<WmsShipmentPlan> list = wmsShipmentPlanExtMapper.getListForNew(paramMap);
            result.setData(list);
            return result;
        } catch (Exception ex) {
            logger.error("WmsShipmentPlanServiceImpl.getShipmentPLanList error : ", ex);
            throw new BusinessException("获取数据异常");
        }
    }

    @Override
    public List<WmsShipmentPlanVehicleDTO> getShipmentPLanVehicleList(String spId) {
        logger.info("WmsShipmentPlanServiceImpl.getShipmentPLanVehicleList param : ", spId);
        if (null == spId || StringUtils.isEmpty(spId)) {
            throw new IllegalArgumentException("参数错误");
        }

        try {
            Long id = Long.parseLong(spId);
            WmsShipmentPlan plan = wmsShipmentPlanMapper.selectByPrimaryKey(id);
            List<WmsShipmentPlanVehicleDTO> list = null;
            if (null != plan && plan.getSpId() > 0) {
                Map<String, Object> paramMap = new HashMap<>();
                String orderByClause = " gmt_create desc ";
                paramMap.put("orderByClause", orderByClause);
                paramMap.put("dispathcNo", plan.getSpDispatchNo());
                paramMap.put("oldModifyTypeNotEquals", WmsShipmentPlanModifyTypeEnum.DELETE.getValue());
                //paramMap.put("sendBusinessFlag", SendBusinessFlagEnum.SEND_N.getValue());
                list = wmsShipmentPlanExtMapper.getShipmentPLanVehicleList(paramMap);
            }
            return list;
        } catch (Exception ex) {
            logger.error("WmsShipmentPlanServiceImpl.getShipmentPLanVehicleList error : ", ex);
            throw new BusinessException("获取数据异常");
        }
    }

    /**
     * 创建备料计划
     * <p>2017-12-28 新需求:创建备料计划时，弹出对话框计划进场时间系统后台自动＋3小时形式</p>
     *
     * @param boList 参数封装
     */
    @Override
    public void createPreparationPlan(List<CreatePreparationPlanBO> boList, String userId) {
        logger.info("WmsShipmentPlanServiceImpl.createPreparationPlan param:{},{} ", boList);
        if (CollectionUtils.isNotEmpty(boList)) {
            for (CreatePreparationPlanBO createPreparationPlanBO : boList) {
                if (null == createPreparationPlanBO || StringUtils.isEmpty(createPreparationPlanBO.getSpId())) {
                    throw new IllegalArgumentException("参数错误");
                }

                Long id = Long.parseLong(createPreparationPlanBO.getSpId());
                WmsShipmentPlan plan = wmsShipmentPlanMapper.selectByPrimaryKey(id);

                if (null != plan && StringUtils.isNotBlank(plan.getSpSendBusinessFlag())
                        && plan.getSpSendBusinessFlag().equals(String.valueOf(SendBusinessFlagEnum.SEND_Y.getValue()))) {
                    throw new IllegalArgumentException("数据已处理");
                }
                if (null != plan && plan.getSpId() > 0) {
                    // 创建备料计划
                    WmsPreparationPlan wmsPreparationPlan = creatWmsPreparationPlan(plan, createPreparationPlanBO);
                    String currentName = getCurrentName(userId);
                    wmsPreparationPlan.setCreateUserName(currentName);
                    wmsPreparationPlan.setPpOperationStaff(currentName);
                    wmsPreparationPlanMapper.insert(wmsPreparationPlan);
                    String no = createWmsPreparationPlanNo(wmsPreparationPlan.getPpId());
                    if (StringUtils.isNotEmpty(no)) {
                        wmsPreparationPlan.setPpPreparationMaterialNo(no);
                        wmsPreparationPlanMapper.updateByPrimaryKeySelective(wmsPreparationPlan);
                    }

                    //WmsShipmentPlanExample example = new WmsShipmentPlanExample();
                    //WmsShipmentPlanExample.Criteria criteria = example.createCriteria();
                    //criteria.andSpDispatchNoEqualTo(plan.getSpDispatchNo());
                    //List<WmsShipmentPlan> list = wmsShipmentPlanMapper.selectByExample(example);
                    //linbao 2017-11-16 只获取未处理且非修改删除的发运计划
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("spDispatchNo", plan.getSpDispatchNo());
                    paramMap.put("spSendBusinessFlag", SendBusinessFlagEnum.SEND_N.getValue());
                    paramMap.put("oldModifyTypeNotEquals", WmsShipmentPlanModifyTypeEnum.DELETE.getValue());
                    List<WmsShipmentPlan> list = wmsShipmentPlanExtMapper.getShipmentList(paramMap);
                    if (CollectionUtils.isNotEmpty(list)) {

                        for (WmsShipmentPlan wsp : list) {
                            // 备料计划详情
                            WmsPreparationVehicleDetail wmsPreparationVehicleDetail = createWmsPreparationVehicleDetail(wmsPreparationPlan, wsp);
                            wmsPreparationVehicleDetail.setCreateUserName(currentName);
                            wmsPreparationVehicleDetailMapper.insert(wmsPreparationVehicleDetail);

                            // 已发送
                            wsp.setSpSendBusinessFlag(SendBusinessFlagEnum.SEND_Y.getValue() + "");
                            wmsShipmentPlanMapper.updateByPrimaryKeySelective(wsp);
                        }
                    }
                }
            }
        }
    }

    /**
     * 生成备料计划 - 君马库
     * <p>
     * 2017-12-28 新需求:创建备料计划时，弹出对话框计划进场时间系统后台自动＋3小时形式
     * 2018-1-23 君马仓库改成以code的方式去生成计划
     * 2018-3-8 君马库生成备料计划之前可能发运计划已经进行过驳回,调整生成备料计划的逻辑
     * </p>
     *
     * @param planBOs 参数封装
     * @throws Exception 异常
     */
    @Override
    public void createPreparationPlanForJunMa(List<CreatePreparationPlanBO> planBOs, String whCode, String userId) throws Exception {

        //校验是否是君马库的发运计划, 并获取发运计划
        List<WmsShipmentPlan> shipmentPlanList = checkCreatePlan(planBOs, whCode);
        //生成备料计划
        if (CollectionUtils.isNotEmpty(shipmentPlanList)) {
            String currentName = getCurrentName(userId);
            Long preparaPlanId = savePreparaPlan(shipmentPlanList, planBOs.get(0), whCode, currentName);
            Map<String, String> destMap = new HashMap<>();
            List<Long> spIdList = new ArrayList<>();

            for (WmsShipmentPlan shipmentPlan : shipmentPlanList) {
                if (shipmentPlan != null) {
                    if (shipmentPlan.getSpGroupBoardQuantity() == null || shipmentPlan.getSpGroupBoardQuantity() <= 0) {
                        throw new BusinessException("存在组版数量为0的发运计划");
                    }
                    //获取库存记录
                    List<WmsInventory> wmsInventoryList = wmsInventoryService.selectInvertoryListForPlanNew(shipmentPlan.getSpMaterialCode(),
                            shipmentPlan.getSpCarColourCode(), shipmentPlan.getSpVehicleCode(), whCode);
                    if (CollectionUtils.isEmpty(wmsInventoryList)) {
                        throw new BusinessException("找不到对应物料编码:" + shipmentPlan.getSpMaterialCode() + "的库存信息");
                    }

                    //获取对应的商品库位
                    //根据批次号排序, 并且库存数量是否足够
                    List<WmsInventoryLocation> locationList = getLocationList(wmsInventoryList, whCode, shipmentPlan.getSpGroupBoardQuantity());
                    //判断库存商品数量是否足够
                    if (shipmentPlan.getSpGroupBoardQuantity() > locationList.size()) {
                        throw new BusinessException("物料编码" + shipmentPlan.getSpMaterialCode() + "正常在库的商品数量不足"
                                + shipmentPlan.getSpGroupBoardQuantity() + "台");
                    }

                    //设置交接单号
                    setHandoverNo(shipmentPlan, destMap);

                    //更新发运计划为已处理
                    //updateShipPlanStatus(shipmentPlan);

                    //更新库存信息为删除 and 更新库存商品的库位为删除
                    //updateInventoryDelete(wmsInventoryList, locationList);

                    savePrepareDetail(shipmentPlan, locationList, preparaPlanId, currentName);

                    spIdList.add(shipmentPlan.getSpId());
                }
            }

            //标记发运计划为已处理
            if (CollectionUtils.isNotEmpty(spIdList)) {
                WmsShipmentPlanExample example = new WmsShipmentPlanExample();
                example.createCriteria().andSpIdIn(spIdList);

                WmsShipmentPlan statusPlan = new WmsShipmentPlan();
                statusPlan.setSpSendBusinessFlag(String.valueOf(SendBusinessFlagEnum.SEND_Y.getValue()));
                wmsShipmentPlanMapper.updateByExampleSelective(statusPlan, example);
            }

            //保存明细和交接单
            //if (CollectionUtils.isNotEmpty(inventoryCustomDTOList)) {
            //    createAndSavePreparationVehicleDetailForJunMa(allCount, inventoryCustomDTOList, preparaPlanId);
            //}
            //if (CollectionUtils.isNotEmpty(shipmentDTOList)) {
            //    createAndSavePreparationVehicleDetailForJunMaNew(shipmentDTOList, preparaPlanId);
            //}
        }
    }

    /**
     * 当前登录用户的名字
     */
    private String getCurrentName(String userId) {
        if (StringUtils.isNotBlank(userId) && StringUtils.isNumeric(userId)) {
            SysUser currentUser = sysUserMapper.selectByPrimaryKey(Integer.parseInt(userId));
            if (currentUser != null) {
                return currentUser.getName();
            }
        }
        return null;
    }

    /**
     * 新版保存明细
     */
    private void createAndSavePreparationVehicleDetailForJunMaNew(List<ShipmentPlanEmptyDTO> shipmentPlanEmptyDTOList,
                                                                  Long preparaPlanId) throws Exception {
        List<WmsHandoverOrder> handoverOrderList = new ArrayList<>();
        List<WmsPreparationVehicleDetail> detailList = new ArrayList<>();
        List<Long> inventoryIdList = new ArrayList<>();
        List<Long> locationIdList = new ArrayList<>();

        for (ShipmentPlanEmptyDTO shipmentPlanEmptyDTO : shipmentPlanEmptyDTOList) {
            if (shipmentPlanEmptyDTO != null) {
                WmsShipmentPlan wmsShipmentPlan = shipmentPlanEmptyDTO.getShipmentPlan();
                if (wmsShipmentPlan != null) {
                    for (int k = 0; k < wmsShipmentPlan.getSpGroupBoardQuantity().intValue(); k++) {
                        WmsInventoryLocation selectLocation = shipmentPlanEmptyDTO.getLocationList().get(k);
                        WmsPreparationVehicleDetail detailNewForJunMa = createWmsPreparationVehicleDetailNewForJunMaOne(preparaPlanId,
                                shipmentPlanEmptyDTO, selectLocation);
                        if (detailNewForJunMa != null) {
                            detailList.add(detailNewForJunMa);
                        }

                        //保存交接单接口信息表
                        WmsHandoverOrder handOrder = saveCreateHandOrder(wmsShipmentPlan, wmsShipmentPlan.getHoHandoverNumber());
                        if (handOrder != null) {
                            if (selectLocation != null) {
                                handOrder.setSernr(selectLocation.getInvlocVin());
                            }
                            handoverOrderList.add(handOrder);
                        }

                        //保存库存库位信息
                        if (selectLocation != null) {
                            locationIdList.add(selectLocation.getInvlocId());
                            inventoryIdList.add(selectLocation.getInvlocInvId());
                        }
                    }
                }
            }

        }
        //锁定库位, 库存
        //deleteInventoryAndLocation(inventoryIdList, locationIdList);
        updateStatusToInventoryAndLocation(locationIdList);

        //批量保存 - 明细
        if (CollectionUtils.isNotEmpty(detailList)) {
            vehicleDetailCustomMapper.insertForBatch(detailList);
        }

        //批量保存 - 交接单
        if (CollectionUtils.isNotEmpty(handoverOrderList)) {
            wmsHandoverOrderCustomMapper.insertForBatch(handoverOrderList);
        }
    }

    /**
     * 保存明细
     */
    private void savePrepareDetail(WmsShipmentPlan wmsShipmentPlan, List<WmsInventoryLocation> locationList,
                                   Long preparaPlanId, String currentName) throws Exception {
        for (int k = 0; k < wmsShipmentPlan.getSpGroupBoardQuantity().intValue(); k++) {
            WmsInventoryLocation selectLocation = locationList.get(k);
            //WmsPreparationVehicleDetail detailNewForJunMa = createWmsPreparationVehicleDetailNewForJunMaOne(preparaPlanId,
            //        shipmentPlanEmptyDTO, selectLocation);
            WmsPreparationVehicleDetail detailNewForJunMa = createWmsPreparationVehicleDetailNewForJunMaTwo(preparaPlanId,
                    wmsShipmentPlan, selectLocation);
            if (detailNewForJunMa != null) {
                //detailList.add(detailNewForJunMa);
                detailNewForJunMa.setCreateUserName(currentName);
                preparationVehicleDetailMapper.insertSelective(detailNewForJunMa);
            }

            //保存交接单接口信息表
            WmsHandoverOrder handOrder = saveCreateHandOrder(wmsShipmentPlan, wmsShipmentPlan.getHoHandoverNumber());
            if (handOrder != null) {
                if (selectLocation != null) {
                    handOrder.setSernr(selectLocation.getInvlocVin());
                }
                //handoverOrderList.add(handOrder);
                handOrder.setCreateUserName(currentName);
                wmsHandoverOrderMapper.insertSelective(handOrder);

            }

            //保存库存库位信息
            if (selectLocation != null) {
                updateStatusToInventoryAndLocationSingle(selectLocation.getInvlocId());
                //locationIdList.add(selectLocation.getInvlocId());
                //inventoryIdList.add(selectLocation.getInvlocInvId());
            }
        }
    }

    /**
     * 设置交接单号
     */
    private void setHandoverNo(WmsShipmentPlan shipmentPlan, Map<String, String> destMap) {

        //根据目的地址生成交接单号
        String destStr = getDestStr(shipmentPlan);
        if (StringUtils.isNotBlank(destStr)) {
            String handoverNo = destMap.get(destStr);
            if (StringUtils.isBlank(handoverNo)) {
                //创建交接单号
                String handoverNumber = createHandoverNumber(shipmentPlan.getSpId());
                destMap.put(destStr, handoverNumber);
                shipmentPlan.setHoHandoverNumber(handoverNumber);
                //更新交接单号
                wmsShipmentPlanMapper.updateByPrimaryKeySelective(shipmentPlan);
            } else {
                shipmentPlan.setHoHandoverNumber(handoverNo);
                wmsShipmentPlanMapper.updateByPrimaryKeySelective(shipmentPlan);
            }
        }
    }


    /**
     * 创建备料计划
     *
     * @param shipmentPlanList        发运计划列表
     * @param createPreparationPlanBO 参数封装
     * @param whCode                  仓库code
     */
    private Long savePreparaPlan(List<WmsShipmentPlan> shipmentPlanList,
                                 CreatePreparationPlanBO createPreparationPlanBO,
                                 String whCode, String currentName) {

        WmsShipmentPlan shipmentPlan = shipmentPlanList.get(0);
        // 创建备料计划
        WmsPreparationPlan wmsPreparationPlan = createWmsPreparationPlanForJunMa(createPreparationPlanBO);
        wmsPreparationPlan.setPpGroupBoardNo(shipmentPlan.getSpGroupBoardNo());//主板单号
        //调拨类型的设置收发货仓库和组版单号
        if (DispatchTypeEnum.A2.getCode().equals(shipmentPlan.getSpDlvType())) {
            wmsPreparationPlan.setPpDlvType(shipmentPlan.getSpDlvType());
            wmsPreparationPlan.setShipWhCode(shipmentPlan.getSpDeliverWarehouseCode());//发货仓库
            wmsPreparationPlan.setDeliverWhCode(shipmentPlan.getSpDealerCode());//收货仓库
            wmsPreparationPlan.setPpDispOrderNo(shipmentPlan.getSpOrderNo());//调拨单号
        }
        wmsPreparationPlan.setPpDlvType(shipmentPlan.getSpDlvType());
        wmsPreparationPlan.setPpWhCode(whCode);
        if (StringUtils.isNotBlank(whCode)) {
            WmsWarehouseBO wmsWarehouseBO = new WmsWarehouseBO();
            wmsWarehouseBO.setWhCode(whCode);
            WmsWarehouse warehouse = wmsWarehouseService.findWarehouseByCode(wmsWarehouseBO);
            if (warehouse != null) {
                wmsPreparationPlan.setPpWhName(warehouse.getWhName());
            }
        }
        //创建人
        wmsPreparationPlan.setCreateUserName(currentName);
        wmsPreparationPlan.setPpOperationStaff(currentName);
        wmsPreparationPlanMapper.insertSelective(wmsPreparationPlan);
        String no = createWmsPreparationPlanNo(wmsPreparationPlan.getPpId());
        if (StringUtils.isNotEmpty(no)) {
            wmsPreparationPlan.setPpPreparationMaterialNo(no);
            wmsPreparationPlanMapper.updateByPrimaryKeySelective(wmsPreparationPlan);
        }
        return wmsPreparationPlan.getPpId();
    }


    /**
     * 获取省市区目的地址
     */
    private String getDestStr(WmsShipmentPlan shipmentPlan) {

        if (shipmentPlan != null) {
            //判断目的地
            StringBuilder destStr = new StringBuilder();
            //2018-4-3  增加经销商code的判断(解决同一地址经销商不同)
            if (StringUtils.isNotBlank(shipmentPlan.getSpDealerCode())) {
                destStr.append(shipmentPlan.getSpDealerCode());
            }
            //省份
            if (StringUtils.isNotBlank(shipmentPlan.getSpProvince())) {
                destStr.append(shipmentPlan.getSpProvince());
            }
            //市
            if (StringUtils.isNotBlank(shipmentPlan.getSpCity())) {
                destStr.append(shipmentPlan.getSpCity());
            }
            //县
            if (StringUtils.isNotBlank(shipmentPlan.getSpDistrictCounty())) {
                destStr.append(shipmentPlan.getSpDistrictCounty());
            }
            //详细地址
            if (StringUtils.isNotBlank(shipmentPlan.getSpDetailedAddress())) {
                destStr.append(shipmentPlan.getSpDetailedAddress());
            }
            if (StringUtils.isNotBlank(destStr)) {
                return destStr.toString();
            }
        }

        return null;
    }

    /**
     * 生成交接单
     */
    private WmsHandoverOrder saveCreateHandOrder(WmsShipmentPlan shipmentPlan, String handorderNumber) {
        WmsHandoverOrder handoverOrder = new WmsHandoverOrder();
        if (shipmentPlan != null) {

            handoverOrder.setVbeln(shipmentPlan.getSpOrderNo());
            if (StringUtils.isNotBlank(shipmentPlan.getSpLineId()) && StringUtils.isNumeric(shipmentPlan.getSpLineId())) {
                handoverOrder.setPosnr(Long.parseLong(shipmentPlan.getSpLineId()));//订单id
            }

            handoverOrder.setZset(shipmentPlan.getSpConfigure());//配置
            //收货仓库 - 经销商
            //if (WarehouseEnum.JM_XY.getWhCode().equals(shipmentPlan.getSpDealerCode())) {
            //    handoverOrder.setZlgort(shipmentPlan.getSpDealerCode());//收货仓库 - 经销商
            //} else if (WarehouseEnum.JM_CS.getWhCode().equals(shipmentPlan.getSpDealerCode())) {
            //
            //}
            handoverOrder.setZlgort(shipmentPlan.getSpDealerCode());//收货仓库 - 经销商

            //发货仓库 - getSpDeliverWarehouseCode
            if (WarehouseEnum.JM_XY.getWhCode().equals(shipmentPlan.getSpDeliverWarehouseCode())) {
                handoverOrder.setLgort(WebServiceWhcodeEnum.XY01.getValue());//接收仓库
            } else if (WarehouseEnum.JM_CS.getWhCode().equals(shipmentPlan.getSpDeliverWarehouseCode())) {
                handoverOrder.setLgort(WebServiceWhcodeEnum.CS01.getValue());//接收仓库
            }

            handoverOrder.setZmode(shipmentPlan.getSpVehicleCode());//车型
            handoverOrder.setSernr(shipmentPlan.getSpVin());//原车架号
            handoverOrder.setGbno(shipmentPlan.getSpGroupBoardNo());//组版单号
            handoverOrder.setZaction(shipmentPlan.getSpDlvType());//发运类型
            handoverOrder.setMatnr(shipmentPlan.getSpMaterialCode());//物料代码
            handoverOrder.setZcol(shipmentPlan.getSpCarColour());//颜色
        }
        //设置备料状态,便于接口按照组办单号发送数据
        handoverOrder.setPreparationStatus(String.valueOf(WmsPreparationPlanEnum.WMS_PLAN_NEW.getValue()));
        handoverOrder.setZdoc(handorderNumber);//交接单号
        handoverOrder.setMbdat(new Date());//交接日期
        handoverOrder.setSendStatus(HandoverSendStatusEnum.NO_SEND.getStatusCode());//发送状态
        handoverOrder.setGmtCreate(new Date());
        handoverOrder.setGmtUpdate(new Date());
        handoverOrder.setCreateUserName("");
        handoverOrder.setModifyUserName("");
        handoverOrder.setSendStatusSap(SendStatusEnum.SEND_INIT.getValue());
        handoverOrder.setSendStatusCrm(SendStatusEnum.SEND_INIT.getValue());
        handoverOrder.setSendStatusTms(SendStatusEnum.SEND_INIT.getValue());
        //handoverOrder.setZsernr("");//替换车架号 - 暂时不需要填写
        //handoverOrder.setWerks("");//交货工厂 - 不用写值
        //handoverOrder.setVstel("");//装运点 - 不用写值
        return handoverOrder;
    }

    /**
     * 更新发运计划为已处理
     */
    private void updateShipPlanStatus(WmsShipmentPlan shipmentPlan) {
        WmsShipmentPlan updateShipPlan = new WmsShipmentPlan();
        updateShipPlan.setSpId(shipmentPlan.getSpId());
        updateShipPlan.setSpSendBusinessFlag(String.valueOf(SendBusinessFlagEnum.SEND_Y.getValue()));
        wmsShipmentPlanMapper.updateByPrimaryKey(updateShipPlan);
    }

    /**
     * 更新库存已删除
     */
    private void updateInventoryDelete(List<WmsInventory> wmsInventoryList, List<WmsInventoryLocation> locationList) throws Exception {
        List<Long> inventoryIdList = new ArrayList<>();
        wmsInventoryList.stream()
                .filter(inven -> inven != null && inven.getInvId() != null)
                .forEach(inven -> inventoryIdList.add(inven.getInvId()));

        List<Long> localtionIdList = new ArrayList<>();
        locationList.stream()
                .filter(location -> location != null && location.getInvlocId() != null)
                .forEach(location -> localtionIdList.add(location.getInvlocId()));

        //删除库存
        if (CollectionUtils.isNotEmpty(inventoryIdList)) {
            wmsInventoryService.deleteInventoryForBatch(inventoryIdList);
        }
        //删除库存对应商品库位
        if (CollectionUtils.isNotEmpty(localtionIdList)) {
            wmsInventoryService.deleteLocationForBatch(localtionIdList);
        }
    }

    /**
     * 删除
     */
    private void deleteInventoryAndLocation(List<Long> inventoryIdList, List<Long> localtionIdList) throws Exception {
        //删除库存
        if (CollectionUtils.isNotEmpty(inventoryIdList)) {
            wmsInventoryService.deleteInventoryForBatch(inventoryIdList);
        }
        //删除库存对应商品库位
        if (CollectionUtils.isNotEmpty(localtionIdList)) {
            wmsInventoryService.deleteLocationForBatch(localtionIdList);
        }
    }

    /**
     * 更新状态锁定
     */
    private void updateStatusToInventoryAndLocation(List<Long> localtionIdList) throws Exception {
        //更新状态锁定
        if (CollectionUtils.isNotEmpty(localtionIdList)) {
            wmsInventoryService.updateStatusLocationForBatch(localtionIdList, InventoryLocationStatusEnum.DEST_LOCK_20.getCode());
        }
    }

    private void updateStatusToInventoryAndLocationSingle(Long id) throws Exception {
        //更新状态锁定
        if (id != null) {
            wmsInventoryService.updateStatusLocation(id, InventoryLocationStatusEnum.DEST_LOCK_20.getCode());
        }
    }

    /**
     * 获取库存商品
     */
    private List<WmsInventoryLocation> getLocationList(List<WmsInventory> wmsInventoryList, String whCode, Long count) {
        if (CollectionUtils.isNotEmpty(wmsInventoryList)) {
            List<Long> invIdList = new ArrayList<>();
            wmsInventoryList.stream()
                    .filter(Objects::nonNull)
                    .filter(inventory -> inventory.getInvId() != null)
                    .forEach(inventory -> invIdList.add(inventory.getInvId()));
            if (CollectionUtils.isNotEmpty(invIdList)) {
                //return wmsInventoryService.listInventoryLocation(invIdList, whCode);
                List<WmsInventoryLocation> locationList = wmsInventoryService.listInventoryLocationForNormal(invIdList, whCode, count.intValue());
                if (CollectionUtils.isNotEmpty(locationList)) {
                    return locationList;
                } else {
                    return wmsInventoryService.listInventoryLocationForNormalBatchNoIsNull(invIdList, whCode, count.intValue());
                }
                //return wmsInventoryService.listInventoryLocationForNormal(invIdList, whCode, count.intValue());
                //listInventoryLocationForNormalBatchNoIsNull
            }
        }
        return null;
    }

    /**
     * 根据库存获取对应的库存库位信息
     */
    private WmsInventoryLocation getLocation(Long parentId) throws Exception {
        if (parentId != null) {
            return wmsInventoryService.getInventoryLocationByParentId(parentId);
        }
        return null;
    }

    /**
     * 前置校验
     *
     * @param bos 参数封装
     */
    private List<WmsShipmentPlan> checkCreatePlan(List<CreatePreparationPlanBO> bos, String whCode) {
        if (CollectionUtils.isEmpty(bos)) {
            throw new BusinessException("请选择数据");
        }
        List<Long> spIdList = new ArrayList<>();
        bos.stream()
                .filter(Objects::nonNull)
                .filter(bo -> StringUtils.isNotBlank(bo.getSpId()))
                .filter(bo -> StringUtils.isNumeric(bo.getSpId()))
                .forEach(bo -> spIdList.add(Long.parseLong(bo.getSpId())));
        if (CollectionUtils.isEmpty(spIdList)) {
            throw new BusinessException("选择数据不正确");
        }

        WmsShipmentPlanExample example = new WmsShipmentPlanExample();
        WmsShipmentPlanExample.Criteria criteria = example.createCriteria();
        criteria.andSpIdIn(spIdList);
        int allCount = wmsShipmentPlanMapper.countByExample(example);

        criteria.andSpSendBusinessFlagEqualTo(String.valueOf(SendBusinessFlagEnum.SEND_N.getValue()));
        int sendedCount = wmsShipmentPlanMapper.countByExample(example);
        if (allCount <= 0 && sendedCount != allCount) {
            throw new BusinessException("存在已处理发运计划");
        }

        criteria.andSpSysSourceEqualTo(WmsSysSourceEnum.DCS_IMPORT.getValue());
        criteria.andSpWhCodeEqualTo(whCode);
        int selectCount = wmsShipmentPlanMapper.countByExample(example);

        if (allCount <= 0 && selectCount != allCount) {
            throw new BusinessException("非同一个仓库数据来源, 不可生成备料计划");
        }

        //校验是否是相同的组版单号
        List<WmsShipmentPlan> wmsShipmentPlanList = wmsShipmentPlanMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(wmsShipmentPlanList)) {
            throw new BusinessException("找不到对应的发运计划数据");
        }
        WmsShipmentPlan wmsShipmentPlan = wmsShipmentPlanList.get(0);
        if (wmsShipmentPlan == null || StringUtils.isBlank(wmsShipmentPlan.getSpGroupBoardNo())) {
            throw new BusinessException("存在组板单号为空的发运计划");
        }

        criteria.andSpGroupBoardNoEqualTo(wmsShipmentPlan.getSpGroupBoardNo());
        List<WmsShipmentPlan> conditionPlanList = wmsShipmentPlanMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(conditionPlanList)
                || conditionPlanList.size() != wmsShipmentPlanList.size()) {
            throw new BusinessException("存在不一致的组板单号");
        }
        //if (CollectionUtils.isNotEmpty(wmsShipmentPlanList)) {
        //    for (WmsShipmentPlan sp : wmsShipmentPlanList) {
        //        if (sp != null) {
        //            if (StringUtils.isBlank(sp.getSpMaterialCode()) || StringUtils.isBlank(sp.getSpVehicleName())
        //                    || StringUtils.isBlank(sp.getSpCarColour())) {
        //                throw new BusinessException("存在物料编码, 车型或颜色为空的发运计划");
        //            }
        //        }
        //    }
        //}
        //获取相同主板单号下的所有计划
        WmsShipmentPlanExample groupBoardNoExample = new WmsShipmentPlanExample();
        groupBoardNoExample.createCriteria()
                .andSpSendBusinessFlagEqualTo(String.valueOf(SendBusinessFlagEnum.SEND_N.getValue()))
                //增加过滤未驳回
                .andSpIsRejectEqualTo(ShipmentPlanRejectStatusEnum.NO_REJECT.getCode())
                .andSpGroupBoardNoEqualTo(wmsShipmentPlan.getSpGroupBoardNo());
        List<WmsShipmentPlan> groupBoardShipmentList = wmsShipmentPlanMapper.selectByExample(groupBoardNoExample);
        if (CollectionUtils.isNotEmpty(groupBoardShipmentList)) {
            for (WmsShipmentPlan sp : groupBoardShipmentList) {
                if (sp != null) {
                    if (StringUtils.isBlank(sp.getSpMaterialCode()) || StringUtils.isBlank(sp.getSpVehicleName())
                            || StringUtils.isBlank(sp.getSpCarColourCode())) {
                        throw new BusinessException("存在物料编码, 车型或颜色编码为空的发运计划");
                    }
                }
            }
        }
        //return wmsShipmentPlanList;
        return groupBoardShipmentList;
    }

    /**
     * 从tms抓取发运计划
     */
    @Override
    public void fetchShipmentPlanListFromTMS() {
        logger.info("WmsShipmentPlanServiceImpl.fetchShipmentPlanListFromTMS param :{}");

        //加入spring的上下文
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        //WAREHOUSE = new String(WAREHOUSE.getBytes("ISO-8859-1"), "utf-8");
        String result = callTms();

        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String msg = jsonObject.getString("message");
            String total = jsonObject.getString("total");
            String records = jsonObject.getString("records");
            Boolean success = jsonObject.getBoolean("success");
            if (!success) {
                logger.error("TmsInspectServiceImpl.callTms error msg: {}", msg);
                throw new BusinessException(msg);
            }
            if (Integer.parseInt(total) >= 1) {
                List<WmsShipmentPlanFromTmsBO> tmsBOList = JSONArray.parseArray(records, WmsShipmentPlanFromTmsBO.class);
                ArrayList<WmsShipmentPlan> insertShips = Lists.newArrayList();
                tmsBOList.forEach((WmsShipmentPlanFromTmsBO v) -> {
                    //存入数据到数据库(写入之前进行重复校验)
                    WmsShipmentPlanExample planExample = new WmsShipmentPlanExample();
                    //重写发运计划获取的重复性校验--如果有重复数据定时任务只能更新以http定时抓取的数据,不能修改mq的数据
                    planExample.or().andSpDispatchNoEqualTo(v.getShipno())
                            .andSpVinEqualTo(v.getVin())
                            .andSpOrderNoEqualTo(v.getOrderno())
                            .andSpWhCodeEqualTo(WhCodeEnum.UNLCN_XN_CQ.getValue());
                    List<WmsShipmentPlan> shipmentPlans = wmsShipmentPlanMapper.selectByExample(planExample);

                    if (CollectionUtils.isEmpty(shipmentPlans)) {
                        //新增
                        WmsShipmentPlan plan = new WmsShipmentPlan();
                        plan.setGmtCreate(new Date());
                        plan.setGmtUpdate(new Date());
                        plan.setSpCustomerName(v.getCustomer());//货主对应TMS客户
                        plan.setSpWaybillNo(v.getCustshipno());
                        plan.setSpOrderNo(v.getOrderno());
                        plan.setSpVin(v.getVin());
                        plan.setSpWhName(WhCodeEnum.UNLCN_XN_CQ.getText());//仓库名
                        plan.setSpWhCode(WhCodeEnum.UNLCN_XN_CQ.getValue());//仓库code
                        plan.setSpVehicleName(v.getStyle());
                        plan.setSpVehicleDesc(v.getStyleDesc());
                        plan.setSpOrigin(v.getOrigin());
                        plan.setSpDest(v.getDest());
                        plan.setCreateUserName("HTTP");
                        plan.setSpDispatchNo(v.getShipno());//调度单号对应tms调度指令号
                        //plan.setSpShipno(v.getShipno());
                        plan.setSpCarrier(v.getSupplier());//承运商对应tms分供方
                        plan.setSpSupplierVehiclePlate(v.getVehicle());

                        plan.setShipmentSource(WmsShipmentSourceEnum.HTTP.getValue());//设置发运计划的来源是定时任务
                        plan.setSpEstimateLoadingTime(new Date());

                        plan.setSpSendBusinessFlag(String.valueOf(SendBusinessFlagEnum.SEND_N.getValue()));//未同步到业务表
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        try {
                            if (StringUtils.isNotBlank(v.getDtship())) {
                                plan.setSpDtship(sdf.parse(v.getDtship()));
                            }
                        } catch (ParseException e) {
                            logger.error("WmsShipmentPlanServiceImpl.fetchShipmentPlanListFromTMS error : ", e);
                            throw new BusinessException("日期转换异常!");
                        }
                        plan.setSpRouteEnd(v.getRoute_end());
                        plan.setSpSysSource(WmsSysSourceEnum.TMS.getValue());
                        if (StringUtils.isNotBlank(v.getOrigin()) && !(WhCodeEnum.UNLCN_XN_CQ.getText().equals(v.getOrigin()))) {
                            //始发地是重庆前置库的数据不是重庆前置库--逻辑删除
                            plan.setOldModifyType(WmsShipmentPlanModifyTypeEnum.DELETE.getValue());
                        }
                        insertShips.add(plan);
                        //wmsShipmentPlanMapper.insertSelective(plan);
                    }
                });
                if (CollectionUtils.isNotEmpty(insertShips)) {
                    wmsShipmentPlanExtMapper.insertShipmentBatch(insertShips);
                }
            }
        }

    }

    /**
     * 旧的更新发运指令的方法
     */
    @Override
    public void updateShipmentPlanByInfo(List<WmsShipmentPlan> wmsShipmentPlanList) {
        if (CollectionUtils.isNotEmpty(wmsShipmentPlanList) && wmsShipmentPlanList.size() > 0) {
            wmsShipmentPlanList.forEach(v -> {
                WmsShipmentPlanExample planExample = new WmsShipmentPlanExample();
                planExample.createCriteria().andSpOrderNoEqualTo(v.getSpOrderNo()).andSpRouteEndEqualTo(v.getSpRouteEnd());
                v.setGmtUpdate(new Date());
                v.setModifyUserName("TMS");
                wmsShipmentPlanMapper.updateByExampleSelective(v, planExample);
            });
        }
    }

    /**
     * 获取发运计划
     */
    @Override
    public WmsShipmentPlan getShipmentPlanById(Long spId) {
        if (spId != null) {
            return wmsShipmentPlanMapper.selectByPrimaryKey(spId);
        }
        return null;
    }

    /**
     * 根据交接单号获取发运计划
     */
    @Override
    public List<WmsShipmentPlan> getShipmentPlanListByHandoverNo(String handoverNo) {
        logger.info("WmsShipmentPlanServiceImpl.getShipmentPlanListByHandoverNo handoverNo: {}", handoverNo);
        if (StringUtils.isNotBlank(handoverNo)) {

            WmsShipmentPlanExample example = new WmsShipmentPlanExample();
            example.createCriteria().andHoHandoverNumberEqualTo(handoverNo);
            return wmsShipmentPlanMapper.selectByExample(example);
        }
        return null;
    }

    /**
     * 根据车架号查询发运计划
     */
    @Override
    public WmsShipmentPlan getShipmentPlanByVin(String vin) {
        if (StringUtils.isNotBlank(vin)) {
            WmsShipmentPlanExample example = new WmsShipmentPlanExample();
            example.createCriteria().andSpVinEqualTo(vin);
            List<WmsShipmentPlan> shipmentPlanList = wmsShipmentPlanMapper.selectByExample(example);
            if (CollectionUtils.isNotEmpty(shipmentPlanList)) {
                return shipmentPlanList.get(0);
            }
        }
        return null;
    }

    /**
     * 根据物料编码, 颜色, 车型名称, 仓库获取发运计划
     */
    @Override
    public WmsShipmentPlan getShipmentByMateriaCodeAndColorAndVehicel(String materiaCode, String color, String vehicle, String whCode) {
        logger.info("WmsShipmentPlanServiceImpl.getShipmentByMateriaCodeAndColorAndVehicel materiaCode: {}, color: {}, vehicle: {}, whCode: {}",
                materiaCode, color, vehicle, whCode);
        if (StringUtils.isNotBlank(materiaCode)
                && StringUtils.isNotBlank(color)
                && StringUtils.isNotBlank(vehicle)
                && StringUtils.isNotBlank(whCode)) {
            WmsShipmentPlanExample example = new WmsShipmentPlanExample();
            example.setOrderByClause(" gmt_create desc, sp_id desc");
            example.createCriteria()
                    .andSpMaterialCodeEqualTo(materiaCode)
                    .andSpCarColourEqualTo(color)
                    .andSpVehicleNameEqualTo(vehicle)
                    .andSpWhCodeEqualTo(whCode)
                    .andSpSysSourceEqualTo(WmsSysSourceEnum.DCS_IMPORT.getValue());
            List<WmsShipmentPlan> wmsShipmentPlanList = wmsShipmentPlanMapper.selectByExample(example);
            if (CollectionUtils.isNotEmpty(wmsShipmentPlanList)) {
                return wmsShipmentPlanList.get(0);
            }
        }
        return null;
    }

    /**
     * 新的更新发运计划的方法()
     */
    @Override
    public void updateShipmentPlanByInfoNew(List<WmsShipmentPlan> wmsShipmentPlanList,
                                            String shipno,
                                            String timestamp) {
        logger.info("WmsShipmentPlanServiceImpl.updateShipmentPlanByInfoNew param : {},{},{}", wmsShipmentPlanList, shipno, timestamp);
        WmsShipmentPlanExample planExample = new WmsShipmentPlanExample();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (CollectionUtils.isNotEmpty(wmsShipmentPlanList) && wmsShipmentPlanList.size() > 0) {
            //1.看发运指令在wms已经存在的数据 (发运指令已经是在wms存在的数据，如果定时任务还没获取到对应的指令数据的话就以mq的数据插入)
            if (StringUtils.isNotBlank(shipno)) {
                //先查对应指令号是否存在
                planExample.createCriteria().andSpDispatchNoEqualTo(shipno);
                List<WmsShipmentPlan> wmsShipmentPlans = wmsShipmentPlanMapper.selectByExample(planExample);
                if (CollectionUtils.isEmpty(wmsShipmentPlans)) {
                    //说明是mq推送的新的修改的发运指令数据,因为定时任务还没有执行,以mq消息为准,插入mq对应的指令号数据
                    //如果是本地不存在的发运指令数据--插入新的发运指令数据
                    wmsShipmentPlanList.forEach((WmsShipmentPlan v) -> {
                        WmsShipmentPlan plan = new WmsShipmentPlan();
                        BeanUtils.copyProperties(v, plan);
                        plan.setGmtCreate(new Date());
                        plan.setGmtUpdate(new Date());
                        plan.setSpWhName(WhCodeEnum.UNLCN_XN_CQ.getText());//仓库名
                        plan.setSpWhCode(WhCodeEnum.UNLCN_XN_CQ.getValue());//仓库code
                        plan.setSpSendBusinessFlag(String.valueOf(SendBusinessFlagEnum.SEND_N.getValue()));//未同步到业务表
                        plan.setSpSysSource(WmsSysSourceEnum.TMS.getValue());
                        getTimeStampForMQ(timestamp, sdf, plan);
                        plan.setCreateUserName("TMS_MQ");
                        plan.setModifyUserName("TMS_MQ");
                        plan.setShipmentSource(WmsShipmentSourceEnum.MQ_ADD.getValue());
                        plan.setOldModifyType(WmsShipmentPlanModifyTypeEnum.ADD.getValue());  //设置对应的修改类型
                        wmsShipmentPlanMapper.insertSelective(plan);
                    });

                } else {
                    //指令已经存在
                    //1.先比较时间戳--时间戳大的就更新
                    Date ts = null;
                    if (StringUtils.isNotBlank(timestamp)) {
                        try {
                            ts = sdf.parse(timestamp); //设置mq的消息消费时间戳
                        } catch (ParseException e) {
                            logger.error("WmsShipmentPlanServiceImpl.updateShipmentPlanByInfoNew error: ", e);
                            throw new BusinessException("日期转换异常!");
                        }
                    }
                    //遍历更新的发运计划列表
                    Iterator<WmsShipmentPlan> planIterator = wmsShipmentPlanList.iterator();
                    ArrayList<String> newVinList = Lists.newArrayList();
                    while (planIterator.hasNext()) {
                        WmsShipmentPlan newPlan = planIterator.next();
                        //已mq的车架号去本地查询对应的车架号信息
                        WmsShipmentPlanExample example = new WmsShipmentPlanExample();
                        example.createCriteria().andSpDispatchNoEqualTo(shipno)
                                .andSpVinEqualTo(newPlan.getSpVin())
                                .andSpWhCodeEqualTo(WhCodeEnum.UNLCN_XN_CQ.getValue());
                        List<WmsShipmentPlan> findOldPlans = wmsShipmentPlanMapper.selectByExample(example);
                        if (CollectionUtils.isNotEmpty(findOldPlans)) {
                            //找到老的
                            WmsShipmentPlan oldPlan = findOldPlans.get(0);
                            //如果本地已经存在该车，比较时间戳,更新为mq修改；
                            //车架号一样不影响我们的备料--比较mq时间戳
                            if (oldPlan.getMqTimestamp() != null) {
                                //时间戳比mq上消息时间戳 小需要更新数据
                                if (ts != null) {
                                    if (oldPlan.getMqTimestamp().before(ts)) {
                                        if (StringUtils.isNotBlank(oldPlan.getOldModifyType()) &&
                                                WmsShipmentPlanModifyTypeEnum.DELETE.getValue().equals(oldPlan.getOldModifyType())) {
                                            //说明这次是要新增；
                                            updateOldVinTOModify(ts, newPlan, oldPlan);
                                            oldPlan.setOldModifyType(WmsShipmentPlanModifyTypeEnum.ADD.getValue());
                                            oldPlan.setShipmentSource(WmsShipmentSourceEnum.MQ_ADD.getValue());
                                            oldPlan.setSpSendBusinessFlag(String.valueOf(SendBusinessFlagEnum.SEND_N.getValue()));
                                            wmsShipmentPlanMapper.updateByPrimaryKeySelective(oldPlan);
                                        } else if (StringUtils.isNotBlank(oldPlan.getOldModifyType()) &&
                                                WmsShipmentPlanModifyTypeEnum.ADD.getValue().equals(oldPlan.getOldModifyType())) {
                                            //说明这次状态还是新增；
                                            updateOldVinTOModify(ts, newPlan, oldPlan);
                                            oldPlan.setOldModifyType(WmsShipmentPlanModifyTypeEnum.ADD.getValue());
                                            wmsShipmentPlanMapper.updateByPrimaryKeySelective(oldPlan);

                                        } else {
                                            //正常修改
                                            updateOldVinTOModify(ts, newPlan, oldPlan);
                                            oldPlan.setOldModifyType(WmsShipmentPlanModifyTypeEnum.NORMAL.getValue());
                                            wmsShipmentPlanMapper.updateByPrimaryKeySelective(oldPlan);
                                        }
                                    }
                                }
                            } else {
                                //如果时间戳为空   直接更新数据
                                if (ts != null) {
                                    updateOldVinTOModify(ts, newPlan, oldPlan);
                                    oldPlan.setOldModifyType(WmsShipmentPlanModifyTypeEnum.NORMAL.getValue());
                                    wmsShipmentPlanMapper.updateByPrimaryKeySelective(oldPlan);
                                }
                            }
                        } else {
                            //如果没有本地查到该车,就mq新增；
                            //车架号不在我们的本地列表中--mq修改新增
                            WmsShipmentPlan plan = new WmsShipmentPlan();
                            BeanUtils.copyProperties(newPlan, plan);
                            plan.setSpEstimateLoadingTime(newPlan.getSpEstimateLoadingTime());
                            plan.setGmtCreate(new Date());
                            plan.setGmtUpdate(new Date());
                            plan.setSpWhName(WhCodeEnum.UNLCN_XN_CQ.getText());//仓库名
                            plan.setSpWhCode(WhCodeEnum.UNLCN_XN_CQ.getValue());//仓库code
                            plan.setCreateUserName("TMS_MQ");
                            plan.setModifyUserName("TMS_MQ");
                            plan.setSpSendBusinessFlag(String.valueOf(SendBusinessFlagEnum.SEND_N.getValue()));//未同步到业务表
                            plan.setSpSysSource(WmsSysSourceEnum.TMS.getValue());
                            if (ts != null) {
                                plan.setMqTimestamp(ts);
                            }
                            plan.setShipmentSource(WmsShipmentSourceEnum.MQ_ADD.getValue());
                            plan.setOldModifyType(WmsShipmentPlanModifyTypeEnum.ADD.getValue());  //设置对应的修改类型
                            wmsShipmentPlanMapper.insertSelective(plan);
                        }
                        newVinList.add(newPlan.getSpVin());
                    }
                    //遍历完整个新老列表 判断老的发运计划的每一条记录是否是mq推送更新过,没更新过说明是要剔除掉的车架号
                    for (WmsShipmentPlan wmsShipmentPlan : wmsShipmentPlans) {
                        if (CollectionUtils.isEmpty(newVinList)) {
                            updateOldVinToDelete(ts, wmsShipmentPlan);
                        } else {
                            //找到不在newVinlist里面的车架号更新删除
                            if (!newVinList.contains(wmsShipmentPlan.getSpVin())) {
                                //对应指令号的全部更新为mq删除
                                updateOldVinToDelete(ts, wmsShipmentPlan);
                            }
                        }
                    }
                }
            }

        } else {
            //该指令下所有发运计划更新删除(取消指令发运)
            planExample.createCriteria().andSpDispatchNoEqualTo(shipno);
            WmsShipmentPlan wmsShipmentPlan = new WmsShipmentPlan();
            wmsShipmentPlan.setOldModifyType(WmsShipmentPlanModifyTypeEnum.DELETE.getValue());
            wmsShipmentPlan.setModifyUserName(WmsSysSourceEnum.MQ.getValue());
            wmsShipmentPlan.setShipmentSource(WmsShipmentSourceEnum.MQ_MODIFY.getValue());
            getTimeStampForMQ(timestamp, sdf, wmsShipmentPlan);
            wmsShipmentPlanMapper.updateByExampleSelective(wmsShipmentPlan, planExample);
        }
    }

    private void getTimeStampForMQ(String timestamp, SimpleDateFormat sdf, WmsShipmentPlan wmsShipmentPlan) {
        if (StringUtils.isNotBlank(timestamp)) {
            try {
                wmsShipmentPlan.setMqTimestamp(sdf.parse(timestamp)); //设置mq的消息消费时间戳
            } catch (ParseException e) {
                logger.error("WmsShipmentPlanServiceImpl.updateShipmentPlanByInfoNew error : ", e);
                throw new BusinessException("日期转换异常!");
            }
        }
    }


    /**
     * 将mq的消息存到日志表中
     */
    @Override
    public void insertMqToLogNew(String message) {
        logger.info("WmsShipmentPlanServiceImpl.insertMqToLogNew mqMessage : {}", message);
        if (StringUtils.isNotBlank(message)) {
            WmsTmsLogWithBLOBs log = new WmsTmsLogWithBLOBs();
            log.setBody(message);
            log.setUrl("WmsShipmentPlanServiceImpl.MQ_MESSAGE");
            log.setGmtCreate(new Date());
            log.setGmtUpdate(new Date());
            log.setSendType(WmsGateControllerTypeEnum.GATE_IN.getCode());
            log.setParam("TMS_MQ_UPDATE_SHIPMENT");
            wmsTmsLogMapper.insert(log);
        }
    }

    /**
     * <p>
     * 已过时方法，新方法{@link WmsShipmentPlanServiceImpl#insertMqToLogNew(java.lang.String)}
     * </p>
     * 将mq的消息存到日志表中
     */
    @Deprecated
    @Override
    public void insertMqToLog(List<WmsShipmentPlan> wmsShipmentPlanList, String shipno, String timestamp) throws Exception {
        logger.info("WmsShipmentPlanServiceImpl.insertMqToLog param : {},{},{}", wmsShipmentPlanList, shipno, timestamp);
        if (CollectionUtils.isNotEmpty(wmsShipmentPlanList) && wmsShipmentPlanList.size() > 0) {
            WmsShipmentUpdatemqLog wmsShipmentUpdatemqLog = new WmsShipmentUpdatemqLog();
            for (WmsShipmentPlan plan : wmsShipmentPlanList) {
                BeanUtils.copyProperties(plan, wmsShipmentUpdatemqLog);
                wmsShipmentUpdatemqLog.setGmtCreate(new Date());
                wmsShipmentUpdatemqLog.setGmtUpdate(new Date());
                wmsShipmentUpdatemqLog.setSpWhName(WhCodeEnum.UNLCN_XN_CQ.getText());//仓库名
                wmsShipmentUpdatemqLog.setSpWhCode(WhCodeEnum.UNLCN_XN_CQ.getValue());//仓库code
                wmsShipmentUpdatemqLog.setCreateUserName("TMS_MQ");
                wmsShipmentUpdatemqLog.setModifyUserName("TMS_MQ");
                if (StringUtils.isNotBlank(timestamp)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date ts = sdf.parse(timestamp);
                    if (ts != null) {
                        wmsShipmentUpdatemqLog.setMqTimestamp(ts);
                    }
                }
                wmsShipmentUpdatemqLog.setSpSysSource(WmsSysSourceEnum.TMS.getValue());//设置消息来源
                wmsShipmentUpdatemqLogMapper.insertSelective(wmsShipmentUpdatemqLog);
            }
        }
    }

    /**
     * 更新发运计划状态为mq推送的数据
     */
    private void updateOldVinTOModify(Date ts, WmsShipmentPlan newPlan, WmsShipmentPlan oldPlan) {
        //BeanUtils.copyProperties(newPlan, oldPlan);
        oldPlan.setSpDispatchNo(newPlan.getSpDispatchNo());
        oldPlan.setSpWaybillNo(newPlan.getSpWaybillNo());
        oldPlan.setSpVin(newPlan.getSpVin());
        oldPlan.setSpOrderNo(newPlan.getSpOrderNo());
        oldPlan.setSpVehicleName(newPlan.getSpVehicleName());
        oldPlan.setSpVehicleDesc(newPlan.getSpVehicleDesc());
        oldPlan.setSpCustomerName(newPlan.getSpCustomerName());
        oldPlan.setSpCarrier(newPlan.getSpCarrier());
        oldPlan.setSpSupplierVehiclePlate(newPlan.getSpSupplierVehiclePlate());
        oldPlan.setSpOrigin(newPlan.getSpOrigin());
        oldPlan.setSpDest(newPlan.getSpDest());
        oldPlan.setSpDtship(newPlan.getSpDtship());
        oldPlan.setSpRouteEnd(newPlan.getSpRouteEnd());
        oldPlan.setGmtUpdate(new Date());
        oldPlan.setMqTimestamp(ts);
        oldPlan.setModifyUserName("TMS_MQ");
        //oldPlan.setCreateUserName("TMS_MQ");
        oldPlan.setShipmentSource(WmsShipmentSourceEnum.MQ_MODIFY.getValue());

    }

    /**
     * mq更新删除老的发运计划
     */
    private void updateOldVinToDelete(Date ts, WmsShipmentPlan wmsShipmentPlan) {
        //对应指令号的全部更新为mq删除
        if (ts != null) {
            wmsShipmentPlan.setMqTimestamp(ts);
        }
        wmsShipmentPlan.setGmtUpdate(new Date());
        wmsShipmentPlan.setModifyUserName("TMS_MQ");
        wmsShipmentPlan.setOldModifyType(WmsShipmentPlanModifyTypeEnum.DELETE.getValue());
        wmsShipmentPlan.setShipmentSource(WmsShipmentSourceEnum.MQ_MODIFY.getValue());
        wmsShipmentPlanMapper.updateByPrimaryKeySelective(wmsShipmentPlan);
    }


    private String callTms() {
        // 构建URL
        String url = propertyUrl;
        Integer time = Integer.parseInt(propertyTime);
        String encode_key = propertyKey;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("encode-key", encode_key);
        url = url + "/mShipSearch.jspx";
        WmsShipmentPlanExample planExample = new WmsShipmentPlanExample();
        planExample.setOrderByClause("sp_dtship desc");
        planExample.setLimitStart(0);
        planExample.setLimitEnd(1);
        //过滤掉mq的推送修改及新增的时间戳
        WmsShipmentPlanExample.Criteria criteria = planExample.createCriteria();
        criteria.andSpWhCodeEqualTo(WhCodeEnum.UNLCN_XN_CQ.getValue())
                .andShipmentSourceEqualTo(WmsShipmentSourceEnum.HTTP.getValue());
        List<WmsShipmentPlan> shipmentPlans = wmsShipmentPlanMapper.selectByExample(planExample);

        //设置时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = null;
        if (CollectionUtils.isNotEmpty(shipmentPlans)) {
            //获取最后一条指令时间,并以此为时间戳
            WmsShipmentPlan plan = shipmentPlans.get(0);
            Date spDtship = plan.getSpDtship();//获取的最后一条指令时间
            timestamp = sdf.format(spDtship);
        } else {
            //就以当前时间向前推60天作为时间戳
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(new Date());//当前时间
            calendar.add(Calendar.DATE, -60);
            Date date = calendar.getTime();
            timestamp = sdf.format(date);
        }
        map.put("timestamp", timestamp);
        map.put("warehouse", WhCodeEnum.UNLCN_XN_CQ.getText());
        map.put("type", TYPE);
        String result = null;
        try {
            result = HttpRequestUtil.sendHttpPost(url, headerMap, map, time);
            String finalResult = result;
            //记录tms日志
            new Thread(() -> {
                WmsTmsLogWithBLOBs bloBs = new WmsTmsLogWithBLOBs();
                bloBs.setGmtCreate(new Date());
                bloBs.setGmtUpdate(new Date());
                bloBs.setSendType("OUT");
                bloBs.setUrl("WmsShipmentPlanServiceImpl.fetchShipmentFromTMS");
                bloBs.setBody(finalResult);
                bloBs.setParam(JSON.toJSONString(map));
            }).start();
        } catch (Exception e) {
            throw new BusinessException("访问tms接口失败");
        }
        return result;
    }

    /**
     * 发运计划--备料计划
     *
     * @param wsp 发运计划
     * @return 返回值
     */
    private WmsPreparationPlan creatWmsPreparationPlan(WmsShipmentPlan wsp, CreatePreparationPlanBO bo) {
        WmsPreparationPlan wmsPreparationPlan = new WmsPreparationPlan();
        wmsPreparationPlan.setCreateUserName("");
        wmsPreparationPlan.setGmtCreate(new Date());
        wmsPreparationPlan.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
        //wmsPreparationPlan.setIsDeleted(DeleteFlagEnum.HAS_QUIT.getValue() + "");
        wmsPreparationPlan.setPpCarColour(wsp.getSpCarColour());
        wmsPreparationPlan.setPpCarrier(wsp.getSpCarrier());
        wmsPreparationPlan.setPpCity(wsp.getSpCity());
        wmsPreparationPlan.setPpConfigure(wsp.getSpConfigure());
        wmsPreparationPlan.setPpDealerCode(wsp.getSpDealerCode());
        wmsPreparationPlan.setPpDealerName(wsp.getSpDealerName());
        wmsPreparationPlan.setPpDetailedAddress(wsp.getSpDetailedAddress());
        wmsPreparationPlan.setPpDistrictCounty(wsp.getSpDistrictCounty());
        wmsPreparationPlan.setPpDlvType(wsp.getSpDlvType());
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.FORMAT_DATETIME);

        //if (null != bo && StringUtils.isNotEmpty(bo.getEstimateFinishTime())) {
        //    try {
        //        wmsPreparationPlan.setPpEstimateFinishTime(sdf.parse(bo.getEstimateFinishTime()));
        //    } catch (ParseException e) {
        //        logger.error("WmsShipmentPlanServiceImpl.creatWmsPreparationPlan error : ", e);
        //    }
        //}

        wmsPreparationPlan.setPpEstimateLane(bo.getEstimateLane());

        if (null != bo && StringUtils.isNotEmpty(bo.getEstimateLoadingTime())) {
            try {
                Date loadTime = sdf.parse(bo.getEstimateLoadingTime());
                Calendar ca = Calendar.getInstance();
                ca.setTime(loadTime);
                ca.add(Calendar.HOUR_OF_DAY, 3);
                Date finishTime = ca.getTime();
                wmsPreparationPlan.setPpEstimateFinishTime(finishTime);
                wmsPreparationPlan.setPpEstimateLoadingTime(loadTime);
            } catch (ParseException e) {
                logger.error("WmsShipmentPlanServiceImpl.creatWmsPreparationPlan error : ", e);
            }
        }

        wmsPreparationPlan.setPpGroupBoardQuantity(wsp.getSpGroupBoardQuantity());
        //bug fix 2017-11-15
        wmsPreparationPlan.setPpGroupDispNo(wsp.getSpDispatchNo());//指令号
        wmsPreparationPlan.setPpMaterialCode(wsp.getSpMaterialCode());
        wmsPreparationPlan.setPpOperationStaff(null);
        wmsPreparationPlan.setPpOrderNo(wsp.getSpOrderNo());
        //wmsPreparationPlan.setPpOutstockStatus(WmsOutboundStatusEnum.WMS_OUTBOUND_NEW.getValue() + "");
        wmsPreparationPlan.setPpOutstockType(null);
        wmsPreparationPlan.setPpProvince(wsp.getSpProvince());
        wmsPreparationPlan.setPpStatus(WmsPreparationPlanEnum.WMS_PLAN_NEW.getValue() + "");
        wmsPreparationPlan.setPpSupplierVehiclePlate(wsp.getSpSupplierVehiclePlate());
        wmsPreparationPlan.setPpVehicleCode(wsp.getSpVehicleCode());
        wmsPreparationPlan.setPpVehicleName(wsp.getSpVehicleName());
        wmsPreparationPlan.setPpWhCode(wsp.getSpWhCode());
        wmsPreparationPlan.setPpWhName(wsp.getSpWhName());
        wmsPreparationPlan.setVersions(null);
        return wmsPreparationPlan;
    }

    /**
     * 创建备料计划 = 君马库
     *
     * @param bo 参数封装
     * @return 返回值
     */
    private WmsPreparationPlan createWmsPreparationPlanForJunMa(CreatePreparationPlanBO bo) {
        WmsPreparationPlan wmsPreparationPlan = new WmsPreparationPlan();
        wmsPreparationPlan.setCreateUserName("");
        wmsPreparationPlan.setGmtCreate(new Date());
        //wmsPreparationPlan.setIsDeleted(DeleteFlagEnum.HAS_QUIT.getValue() + "");
        wmsPreparationPlan.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.FORMAT_DATETIME);//yyyy-MM-dd HH:mm:ss
        //if (null != bo && StringUtils.isNotEmpty(bo.getEstimateFinishTime())) {
        //    try {
        //        wmsPreparationPlan.setPpEstimateFinishTime(sdf.parse(bo.getEstimateFinishTime()));
        //    } catch (ParseException e) {
        //        logger.error("WmsShipmentPlanServiceImpl.creatWmsPreparationPlan error : ", e);
        //        throw new BusinessException("时间转换错误");
        //    }
        //}
        if (null != bo && StringUtils.isNotEmpty(bo.getEstimateLoadingTime())) {
            try {
                Date loadTime = sdf.parse(bo.getEstimateLoadingTime());
                wmsPreparationPlan.setPpEstimateLoadingTime(loadTime);
                Calendar ca = Calendar.getInstance();
                ca.setTime(loadTime);
                ca.add(Calendar.HOUR_OF_DAY, 3);
                Date finishTime = ca.getTime();
                wmsPreparationPlan.setPpEstimateFinishTime(finishTime);
                wmsPreparationPlan.setPpEstimateLoadingTime(loadTime);
            } catch (ParseException e) {
                logger.error("WmsShipmentPlanServiceImpl.creatWmsPreparationPlan error : ", e);
                throw new BusinessException("时间转换错误");
            }
        }
        wmsPreparationPlan.setPpEstimateLane(bo.getEstimateLane());
        wmsPreparationPlan.setPpStatus(WmsPreparationPlanEnum.WMS_PLAN_NEW.getValue() + "");
        //wmsPreparationPlan.setPpOperationStaff(null);
        //wmsPreparationPlan.setPpOutstockType(null);
        //wmsPreparationPlan.setVersions(null);
        return wmsPreparationPlan;
    }

    /**
     * 备料计划详情
     */
    public WmsPreparationVehicleDetail createWmsPreparationVehicleDetail(WmsPreparationPlan wmsPreparationPlan, WmsShipmentPlan wsp) {
        //判断老项目
        WmsPreparationVehicleDetail oldCopyDetail = getOldCopyDetail(wsp.getSpVin());
        WmsPreparationVehicleDetail wmsPreparationVehicleDetail = new WmsPreparationVehicleDetail();
        if (oldCopyDetail != null) {
            BeanUtils.copyProperties(oldCopyDetail, wmsPreparationVehicleDetail);
            wmsPreparationVehicleDetail.setVdPpId(Long.parseLong(wmsPreparationPlan.getPpId() + ""));
            oldCopyDetail.setIsDeleted(DeleteFlagEnum.DELETED.getValue());
            wmsPreparationVehicleDetailMapper.updateByPrimaryKeySelective(oldCopyDetail);
            //保存变更记录
            if (oldCopyDetail.getVdPpId() != null) {
                WmsPreparationPlan oldPreparaPlan = wmsPreparationPlanMapper.selectByPrimaryKey(oldCopyDetail.getVdPpId());
                if (oldPreparaPlan != null) {
                    saveDetailUpdateRecord(oldPreparaPlan.getPpGroupDispNo(), wsp.getSpDispatchNo(), wsp.getSpVin(),
                            oldPreparaPlan.getPpPreparationMaterialNo(), wmsPreparationPlan.getPpPreparationMaterialNo());
                }
            }
        } else {
            wmsPreparationVehicleDetail.setCreateUserName("");
            wmsPreparationVehicleDetail.setGmtCreate(new Date());
            wmsPreparationVehicleDetail.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
            wmsPreparationVehicleDetail.setVdOutstockStatus(null);
            wmsPreparationVehicleDetail.setVdPpId(Long.parseLong(wmsPreparationPlan.getPpId() + ""));
            wmsPreparationVehicleDetail.setVdVehicleDesc(wsp.getSpVehicleDesc());
            wmsPreparationVehicleDetail.setVdVehicleName(wsp.getSpVehicleName());
            wmsPreparationVehicleDetail.setVdVin(wsp.getSpVin());
            wmsPreparationVehicleDetail.setVdWaybillNo(wsp.getSpWaybillNo());
            wmsPreparationVehicleDetail.setVersions(null);
            wmsPreparationVehicleDetail.setVdOutstockStatus(WmsOutboundStatusEnum.WMS_OUTBOUND_NEW.getValue() + "");
        }
        return wmsPreparationVehicleDetail;
    }

    /**
     * 保存变更记录
     */
    private void saveDetailUpdateRecord(String oldDispNo, String newDispNo, String vin, String oldPpMaterNo, String newPpMaterNo) {
        WmsDetailUpdateRecord record = new WmsDetailUpdateRecord();
        record.setGmtCreate(new Date());
        record.setGmtUpdate(new Date());
        record.setUrOldDispatchNo(oldDispNo);
        record.setUrNewDispatchNo(newDispNo);
        record.setUrVin(vin);
        record.setUrOldPreparationNo(oldPpMaterNo);
        record.setUrNewPreparationNo(newPpMaterNo);
        detailUpdateRecordMapper.insertSelective(record);
    }

    /**
     * 出库管理 - 判断是否有备料计划
     */
    private WmsPreparationVehicleDetail getOldCopyDetail(String vin) {
        if (StringUtils.isNotBlank(vin)) {
            //查询老数据
            WmsPreparationVehicleDetailExample detailExample = new WmsPreparationVehicleDetailExample();
            detailExample.setOrderByClause(" gmt_create desc, vd_id desc");
            detailExample.setLimitStart(0);
            detailExample.setLimitEnd(1);
            detailExample.createCriteria().andVdVinEqualTo(vin);
            List<WmsPreparationVehicleDetail> detailList = wmsPreparationVehicleDetailMapper.selectByExample(detailExample);
            if (CollectionUtils.isNotEmpty(detailList)) {
                WmsPreparationVehicleDetail detail = detailList.get(0);
                if (detail != null) {
                    //如果是已出库
                    if (String.valueOf(WmsOutboundStatusEnum.WMS_OUTBOUND_FINISH.getValue()).equals(detail.getVdOutstockStatus())) {
                        return detail;
                    } else if (String.valueOf(WmsOutboundStatusEnum.WMS_OUTBOUND_NEW.getValue()).equals(detail.getVdOutstockStatus())) {
                        if (String.valueOf(DeleteFlagEnum.NORMAL.getValue()).equals(String.valueOf(detail.getIsDeleted()))) {
                            throw new BusinessException("该车架号" + vin + "存在未完成的计划, 请核实");
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 备料计划详情
     */
    private WmsPreparationVehicleDetail createWmsPreparationVehicleDetailNewForJunMaOne(Long parentId, ShipmentPlanEmptyDTO shipmentPlanEmptyDTO,
                                                                                        WmsInventoryLocation wmsInventoryLocation) throws Exception {
        WmsPreparationVehicleDetail wmsPreparationVehicleDetail = new WmsPreparationVehicleDetail();
        wmsPreparationVehicleDetail.setCreateUserName("");
        wmsPreparationVehicleDetail.setGmtCreate(new Date());
        wmsPreparationVehicleDetail.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
        wmsPreparationVehicleDetail.setVdOutstockStatus(null);
        wmsPreparationVehicleDetail.setVdPpId(parentId);

        if (wmsInventoryLocation != null && wmsInventoryLocation.getInvlocInvId() != null) {
            WmsInventory inventory = wmsInventoryService.getWmsInventoryByPrimaryKey(wmsInventoryLocation.getInvlocInvId());
            if (inventory != null) {
                wmsPreparationVehicleDetail.setVdVehicleDesc(inventory.getInvVehicleSpecDesc());
                wmsPreparationVehicleDetail.setVdVehicleName(inventory.getInvVehicleSpecName());
            }
        }
        if (wmsInventoryLocation != null) {
            wmsPreparationVehicleDetail.setVdVin(wmsInventoryLocation.getInvlocVin());//车架号
            wmsPreparationVehicleDetail.setVdWaybillNo(wmsInventoryLocation.getInvlocWaybillNo());//运单号
        }
        wmsPreparationVehicleDetail.setVersions(null);
        wmsPreparationVehicleDetail.setVdOutstockStatus(WmsOutboundStatusEnum.WMS_OUTBOUND_NEW.getValue() + "");
        WmsShipmentPlan shipmentPlan = shipmentPlanEmptyDTO.getShipmentPlan();
        if (shipmentPlan != null) {
            wmsPreparationVehicleDetail.setHoHandoverNumber(shipmentPlan.getHoHandoverNumber());//交接单号
        }
        return wmsPreparationVehicleDetail;
    }

    /**
     * 备料计划详情
     */
    private WmsPreparationVehicleDetail createWmsPreparationVehicleDetailNewForJunMaTwo(Long parentId, WmsShipmentPlan wmsShipmentPlan,
                                                                                        WmsInventoryLocation wmsInventoryLocation) throws Exception {
        WmsPreparationVehicleDetail wmsPreparationVehicleDetail = new WmsPreparationVehicleDetail();
        wmsPreparationVehicleDetail.setCreateUserName("");
        wmsPreparationVehicleDetail.setGmtCreate(new Date());
        wmsPreparationVehicleDetail.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
        wmsPreparationVehicleDetail.setVdOutstockStatus(null);
        wmsPreparationVehicleDetail.setVdPpId(parentId);

        if (wmsInventoryLocation != null && wmsInventoryLocation.getInvlocInvId() != null) {
            WmsInventory inventory = wmsInventoryService.getWmsInventoryByPrimaryKey(wmsInventoryLocation.getInvlocInvId());
            if (inventory != null) {
                wmsPreparationVehicleDetail.setVdVehicleDesc(inventory.getInvVehicleSpecDesc());
                wmsPreparationVehicleDetail.setVdVehicleName(inventory.getInvVehicleSpecName());
            }
        }
        if (wmsInventoryLocation != null) {
            wmsPreparationVehicleDetail.setVdVin(wmsInventoryLocation.getInvlocVin());//车架号
            wmsPreparationVehicleDetail.setVdWaybillNo(wmsInventoryLocation.getInvlocWaybillNo());//运单号
        }
        wmsPreparationVehicleDetail.setVersions(null);
        wmsPreparationVehicleDetail.setVdOutstockStatus(WmsOutboundStatusEnum.WMS_OUTBOUND_NEW.getValue() + "");
        if (wmsShipmentPlan != null) {
            wmsPreparationVehicleDetail.setHoHandoverNumber(wmsShipmentPlan.getHoHandoverNumber());//交接单号
        }
        return wmsPreparationVehicleDetail;
    }

    /**
     * 备料单号
     */
    public String createWmsPreparationPlanNo(Long id) {
        if (id != null && id > 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String today = sdf.format(new Date());
            String no = "P" + today + "_" + id;
            return no;
        }
        return null;
    }

    /**
     * 创建交接单号
     */
    private String createHandoverNumber(Long id) {
        if (id > 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            StringBuilder num = new StringBuilder(OrderHeadEnum.HANDOVER.getCode());
            num.append(sdf.format(new Date()));
            if (id < 1000) {
                num.append(String.format("%04d", id));
            } else {
                num.append(id);
            }
            return num.toString();
        }
        return null;
    }


    /**
     * 发运计划驳回的接口
     */
    @Override
    public void updateShipmentCancel() throws Exception {
        logger.info("WmsShipmentPlanServiceImpl.updateShipmentCancel param : ");
        //查询未发送的发运计划驳回接口
        WmsShipmentPlanCancelExample cancelExample = new WmsShipmentPlanCancelExample();
        cancelExample.createCriteria().andSendStatusEqualTo(SendStatusEnum.SEND_INIT.getValue());
        cancelExample.setOrderByClause(" id DESC");
        cancelExample.setLimitStart(0);
        cancelExample.setLimitEnd(1);
        List<WmsShipmentPlanCancel> planCancels = wmsShipmentPlanCancelMapper.selectByExample(cancelExample);
        if (CollectionUtils.isNotEmpty(planCancels)) {
            wmsJmDcsService.updateBillCancelAction(planCancels.get(0));
        }
    }


    //private static final int TOTAL_COUNT = 5;

    @Override
    public void updateShipmentCancleExcp() throws Exception {
        logger.info("WmsShipmentPlanServiceImpl.updateShipmentCancleExcp param : ");
        WmsShipmentCancelExcpExample excpExample = new WmsShipmentCancelExcpExample();
        excpExample.createCriteria().andSendStatusEqualTo(SendStatusEnum.SEND_FAILED.getValue())
                .andDcsFinalStatusIsNull();
        excpExample.setOrderByClause(" id DESC");
        excpExample.setLimitStart(0);
        excpExample.setLimitEnd(1);
        List<WmsShipmentCancelExcp> wmsShipmentCancelExcps = wmsShipmentCancelExcpMapper.selectByExample(excpExample);
        if (CollectionUtils.isNotEmpty(wmsShipmentCancelExcps)) {
            WmsShipmentCancelExcp wmsShipmentCancelExcp = wmsShipmentCancelExcps.get(0);
            WmsShipmentPlanCancel planCancel = new WmsShipmentPlanCancel();
            BeanUtils.copyProperties(wmsShipmentCancelExcp, planCancel);
            wmsJmDcsService.updateBillCancelAction(planCancel);
        }

    }

}
